package org.cleverframe.fastdfs.spring.boot.autoconfigure;

import java.util.HashSet;
import java.util.Set;

import org.cleverframe.fastdfs.client.DefaultStorageClient;
import org.cleverframe.fastdfs.client.DefaultTrackerClient;
import org.cleverframe.fastdfs.client.StorageClient;
import org.cleverframe.fastdfs.client.TrackerClient;
import org.cleverframe.fastdfs.conn.DefaultCommandExecutor;
import org.cleverframe.fastdfs.pool.ConnectionPool;
import org.cleverframe.fastdfs.pool.PooledConnectionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
@EnableConfigurationProperties(FdfsProperties.class)
@ConditionalOnProperty(name="fdfs.enabled",havingValue="true",matchIfMissing=false)
public class FdfsAutoConfiguration {
  
  @Bean
  public  DefaultCommandExecutor commandExecutor(FdfsProperties properties) {
	  PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory(properties.getSoTimeout(), properties.getConnectTimeout());
      ConnectionPool connectionPool = new ConnectionPool(pooledConnectionFactory, properties);
      Set<String> trackerSet = new HashSet<>();
      for(String tracker: properties.getTrackers()) {
    	  trackerSet.add(tracker);
      }
      DefaultCommandExecutor commandExecutor = new DefaultCommandExecutor(trackerSet, connectionPool);
      return commandExecutor;
  }
  
  @Bean
  public TrackerClient trackerClient(DefaultCommandExecutor commandExecutor) {
	  TrackerClient trackerClient = new DefaultTrackerClient(commandExecutor);
	  return trackerClient;
  }
  
  @Bean
  public StorageClient storageClient(DefaultCommandExecutor commandExecutor,TrackerClient trackerClient) {
	  StorageClient storageClient = new DefaultStorageClient(commandExecutor, trackerClient);
	  return storageClient;
  }

}
